package cn.edu.xmist.supermarketsys.controller;

import cn.edu.xmist.supermarketsys.Util.Strs;
import cn.edu.xmist.supermarketsys.entity.User;
import cn.edu.xmist.supermarketsys.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private HttpSession httpSession;

    @RequestMapping("/loginHtml")
    public String login() {
        return "login";
    }

    @ResponseBody
    @RequestMapping("/login")
    public String login(User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", user.getUsername());
        List<User> list = userService.list(queryWrapper);
        if (list.size() > 0) {
            if (user.getPassword().equals(list.get(0).getPassword())) {
                httpSession.setAttribute("user", user.getUsername());
                return Strs.SUCCESS_RETURN_JSON;
            }
        }
        return Strs.FAIL_RETURN_JSON;
    }

    @ResponseBody
    @RequestMapping("/logout")
    public String logout() {
        httpSession.invalidate();
        return Strs.SUCCESS_RETURN_JSON;
    }
}
